package engine.gameObject.terrain;

import engine.util.texture.RawData;
import engine.util.texture.TextureLoader;

public class TerrainLoader {

	private TerrainLoader() {}
	
	public static Terrain loadRAW(String file, float verticalScale, int areaSize, float textureScale, float[] textureHeights) {
		RawData data = TextureLoader.loadRawData(file);
		
		float[][] height = new float[data.getWidth()][data.getHeight()];
		
		int dataPerVertex = data.getTextureBuffer().capacity() / (data.getWidth() * data.getHeight());
		
		data.getTextureBuffer().rewind();
		
		for(int i = 0; i < data.getWidth(); i++) {
			for(int j = 0; j < data.getHeight(); j++) {
				for(int k = 0; k < dataPerVertex; k++) {
					height[i][j] += toUnsigned(data.getTextureBuffer().get()); 
				}
				height[i][j] *= verticalScale;
			}
		}
		
		for(int k = 0; k < 3; k++) {
			for(int i = 1; i < data.getWidth() - 1; i++) {
				for(int j = 1; j < data.getHeight() - 1; j++) {
					height[i][j] = (height[i - 1][j] + height[i + 1][j] + height[i][j - 1] + height[i][j + 1]) / 4; 
				}
			}
		}
		
		return new Terrain(height, areaSize, textureScale, textureHeights);
	}
	
	private static int toUnsigned(byte b) {
	    return b & 0xFF;
	}

	
	public static Terrain loadRAW(String file, float verticalScale, int detailAreaSize, float textureScale) {
		return loadRAW(file, verticalScale, detailAreaSize, textureScale, null);
	}
	
	public static Terrain loadRAW(String file, float verticalScale, int detailAreaSize) {
		return loadRAW(file, verticalScale, detailAreaSize, 1, null);
	}
}
